# -*- coding: utf-8 -*-
import datetime

from django.http import JsonResponse
from django.utils import timezone
from django.db.models import Count


from .models import Vote, VoteChoice


def poll(request):
    """
    发起投票
    """
    title = request.body_data.get('title')
    desc = request.body_data.get('desc')
    choices = request.body_data.get('choices')
    is_mult = request.body_data.get('isMult')
    end_time_str = request.body_data.get('endTime')
    end_time = datetime.datetime.strptime(end_time_str, "%Y-%m-%d %H:%M")

    vote = Vote.objects.create_vote(title=title,
                                    desc=desc,
                                    user=request.miniweixin_user,
                                    choices=choices,
                                    is_mult=is_mult,
                                    end_time=end_time)
    return JsonResponse({'code': 0, 'message': u"发起投票成功", 'data': {'id': vote.id}})


def choose(request):
    """
    用户投票
    """
    vote_id = request.body_data.get('id')
    choice_indexs = request.body_data.get('choices')
    try:
        vote = Vote.objects.get(id=vote_id)
    except Vote.DoesNotExist:
        return JsonResponse({'code': 404, 'message': u"该投票不存在", 'data': {}})
    if vote.end_time < timezone.now():
        return JsonResponse({'code': 400, 'message': u"投票已结束", 'data': {}})
    if VoteChoice.objects.filter(user=request.miniweixin_user, vote=vote).exists():
        return JsonResponse({'code': 409, 'message': u"您已经投过票了", 'data': {}})
    if len(choice_indexs) > 1 and not vote.is_mult:
        return JsonResponse({'code': 400, 'message': u"不支持多选", 'data': {}})
    len_choice_list = len(vote.choice_list)
    vote_choice_list = [
        VoteChoice(
            user=request.miniweixin_user, vote=vote, choice=i
        ) for i in set(choice_indexs) if i >= 0 and i < len_choice_list]
    vote_choices = []
    if vote_choice_list:
        vote_choices = VoteChoice.objects.bulk_create(vote_choice_list)
    ids = [i.id for i in vote_choices]
    return JsonResponse({'code': 0, 'message': u"投票成功", 'data': {'ids': ids}})


def vote_detail(request):
    """
    投票详情
    """
    vote_id = request.GET.get('id')
    try:
        vote = Vote.objects.get(id=vote_id)
    except Vote.DoesNotExist:
        return JsonResponse({'code': 404, 'message': u"该投票不存在", 'data': {}})
    # 获取用户投票
    my_choices = list(VoteChoice.objects.filter(vote=vote,
                                                user=request.miniweixin_user).values_list('choice', flat=True))
    detail_info = {
        'title': vote.title,
        'desc': vote.desc,
        'myChoice': my_choices,
        'author': vote.user.nickname,
        'isMult': vote.is_mult,
        'createTime': vote.create_time.strftime("%Y-%m-%d %H:%M"),
        'endTime': vote.end_time.strftime("%Y-%m-%d %H:%M")
    }
    # 每个投票选项的情况，包括投票的人的昵称和头像
    all_choices = VoteChoice.objects.filter(vote=vote).order_by('create_time')
    openid_set = set()
    choice_dict = {}
    for i in all_choices:
        if i.choice not in choice_dict:
            choice_dict[i.choice] = []
        choice_dict[i.choice].append({
            'nickName': i.user.nickname,
            'avatarUrl': i.user.avatar_url
        })
        openid_set.add(i.user.openid)
    # 目前参与投票的人数
    detail_info['joinUserNum'] = len(openid_set)
    # 目前总的票数
    detail_info['totalChoiceNum'] = len(all_choices)
    # 所有选项
    full_choices = [{
        'title': j,
        'num': len(choice_dict.get(i, [])),  # 票数
        'choseUserList': choice_dict.get(i, [])  # 投票人
    } for i, j in enumerate(vote.choice_list)]
    # 如果是本人发起的，则可以查看投票完整情况
    if vote.user == request.miniweixin_user:
        detail_info['choices'] = full_choices
    elif len(my_choices) > 0:
        # 已经投票，只可看每个选择票数
        detail_info['choices'] = [{
            'title': i['title'],
            'num': i['num'],
            'choseUserList': []
        } for i in full_choices]
    else:
        # 未投票，且非发起人，则不可查看投票情况
        detail_info['choices'] = [{
            'title': i['title'],
            'num': -1,
            'choseUserList': []
        } for i in full_choices]
    return JsonResponse({'code': 0, 'message': "获取详情成功", 'data': detail_info})


def vote_list(request):
    """
    本人投票列表
    """
    my_votes = Vote.objects.filter(user=request.miniweixin_user).order_by('-create_time')
    votes = [{
        'id': i.id,
        'title': i.title,
        'createTime': i.create_time.strftime("%Y-%m-%d %H:%M"),
        'joinUserNum': VoteChoice.objects.filter(vote=i).aggregate(cnt=Count('user', distinct=True))['cnt']
    } for i in my_votes]
    return JsonResponse({'code': 0, 'message': u"获取列表成功", 'data': votes})
